package com.avcdata.national.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.avcdata.aoscustommade.R;
import com.avcdata.aoscustommade.activity.Login_Activity;
import com.avcdata.aoscustommade.adapter.MyWheelAdapter;
import com.avcdata.aoscustommade.main.BaseActivity;
import com.avcdata.aoscustommade.utils.AppActivityManager;
import com.avcdata.aoscustommade.utils.AvcConstants;
import com.avcdata.aoscustommade.utils.SharedPreferencesUtils;
import com.avcdata.national.adapter.AreaAdapter;
import com.avcdata.national.module.AreaInfo;
import com.avcdata.national.module.AreaListViewInfo;
import com.avcdata.national.network.BaseLog;
import com.avcdata.national.network.JsonRunnable;
import com.avcdata.national.network.ThreadPoolUtils;
import com.avcdata.national.utils.MyUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.wx.wheelview.widget.WheelView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.avcdata.aoscustommade.R.id.dialog_cancel;
import static com.avcdata.aoscustommade.utils.AvcConstants.URL_Area;

/**
 * NewAOSApp
 * com.avcdata.national.activity
 * Created by lic on 2017/9/23.
 * CSDN http://blog.csdn.net/lucasey
 *
 * 具体城市
 *
 */

public class AreaCityActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    @ViewInject(R.id.left_group)
    private LinearLayout left_group;
    @ViewInject(R.id.leftText)
    private TextView leftText;
    @ViewInject(R.id.right_group)
    private LinearLayout right_group;
    @ViewInject(R.id.title)
    private TextView title;

    @ViewInject(R.id.sale_type)
    private LinearLayout sale_type;
    @ViewInject(R.id.sale_text)
    private TextView sale_text;
    @ViewInject(R.id.week_type)
    private LinearLayout week_type;
    @ViewInject(R.id.week_text)
    private TextView week_text;

    @ViewInject(R.id.title_name)
    private TextView title_name;

    @ViewInject(R.id.lv)
    private ListView lv;

    private AreaAdapter adapter;

    private List<AreaListViewInfo> list = new ArrayList<>();

    private String weekString = "current";
    private String saleString = "amount";
    private String weekStringTemp = "";
    private String saleStringTemp = "";

    @ViewInject(R.id.jiazai_layout)
    private LinearLayout loading;

    private Dialog dialog;
    private ArrayList<String> weeks;
    private ArrayList<String> sales;

    private String category = "";
    private String bigregion = "";
    private String office = "";

    @Override
    public void initView() {
        setContentView(R.layout.activity_national_area);
        AppActivityManager.getAppManager().addActivity(this);
        ViewUtils.inject(this);
    }

    @Override
    public void initInstall() {
        left_group.setOnClickListener(this);
        right_group.setOnClickListener(this);
        right_group.setVisibility(View.GONE);
    }

    @Override
    public void initData() {
        week_type.setOnClickListener(this);
        sale_type.setOnClickListener(this);
        category = getIntent().getStringExtra("category");
        bigregion = getIntent().getStringExtra("bigregion");
        office = getIntent().getStringExtra("office");
        BaseLog.e("办事处页面","品类："+category+",大区："+bigregion+",办事处："+office);
        title.setText(office);
        title_name.setText("城市");
        leftText.setText("返回"+bigregion);
    }

    @Override
    public void evenControl() {
        initOnCreate();
    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.left_group:
                this.finish();
                break;
            case R.id.right_group:
                // TODO: 2017/8/23 分享待接入
                showShare ( getWindow ().getDecorView ().findViewById ( android.R.id.content ) );
                break;
            case R.id.sale_type:
                showDialogSelect(1);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.line_type:
                showDialogSelect(3);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.week_type:
                showDialogSelect(2);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            default:
                break;
        }
    }

    private void initOnCreate() {
        loading.setVisibility(View.GONE);
        weeks = new ArrayList<>();
        weeks.add("当前周");
        weeks.add("近四周");
        weeks.add("近八周");
        weeks.add("本年累计");
        sales = new ArrayList<>();
        sales.add("销量");
        sales.add("销额");
        //设置周度
        switch (new SharedPreferencesUtils(this).getWeekType()) {
            case "近四周":
                week_text.setText("近四周");
                weekString = "fourWeek";
                break;
            case "近八周":
                week_text.setText("近八周");
                weekString = "eightWeek";
                break;
            case "本年累计":
                week_text.setText("本年累计");
                weekString = "year";
                break;
            case "当前周":
                week_text.setText("当前周");
                weekString = "current";
                break;
            default:
                week_text.setText("当前周");
                weekString = "current";
                break;
        }
        //设置销量销额方式
        if (new SharedPreferencesUtils(this).getSaleType() == 1) {
            sale_text.setText("销量");
            saleString = "volume";
        } else {
            sale_text.setText("销额");
            saleString = "amount";
        }

        adapter = new AreaAdapter(list,this);
        lv.setAdapter(adapter);

        getBrandScaleBasisRatio();
    }


    /***
     * 获取选择的索引
     * @param dataTemp
     * @param stringTemp
     * @return
     */
    private int getSelectPosition(ArrayList<String> dataTemp, String stringTemp) {
        int temp = 0;
        for (int i = 0; i < dataTemp.size(); i++) {
            if (dataTemp.get(i).equals(stringTemp)) {
                temp = i;
            }
        }
        return temp;
    }


    /***
     *单选dialog
     * @param dialogNum 3-线上线下/2-最新周···
     */
    private void showDialogSelect(final int dialogNum) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_single, null);
        dialog = new Dialog(this, R.style.DialogBlack);
        Window window = dialog.getWindow();
        window.setContentView(view);
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.CENTER);

        final TextView dialog_title1 = (TextView) view.findViewById(R.id.dialog_title1);
        TextView dialog_title2 = (TextView) view.findViewById(R.id.dialog_title2);
        final WheelView wheelview_single1 = (WheelView) view.findViewById(R.id.wheelview_single1);
        final WheelView wheelview_single2 = (WheelView) view.findViewById(R.id.wheelview_single2);
        dialog_title2.setVisibility(View.GONE);
        wheelview_single2.setVisibility(View.GONE);
        wheelview_single1.setSkin(WheelView.Skin.None);
        WheelView.WheelViewStyle style = new WheelView.WheelViewStyle();
        style.selectedTextColor = Color.RED;
        style.selectedTextSize = 20;
        style.textColor = Color.BLACK;
        wheelview_single1.setStyle(style);
        wheelview_single1.setLoop(false);
        wheelview_single1.setWheelClickable(false);
        switch (dialogNum) {
            case 1:
                dialog_title1.setText("选择销量销额");
                wheelview_single1.setWheelData(sales);
                wheelview_single1.setSelection(getSelectPosition(sales, saleStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(this));
                break;
            case 2:
                dialog_title1.setText("选择周度时长");
                wheelview_single1.setWheelData(weeks);
                wheelview_single1.setSelection(getSelectPosition(weeks, weekStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(this));
                break;
            default:
                break;
        }

        view.findViewById(dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });

        view.findViewById(R.id.dialog_ensure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (dialogNum) {
                    case 1:
                        saleStringTemp = sales.get(wheelview_single1.getCurrentPosition());
                        sale_text.setText(saleStringTemp);
                        if (sales.get(wheelview_single1.getCurrentPosition()).equals("销量")) {
                            saleString = "volune";
                            sale_text.setText("销量");
                            new SharedPreferencesUtils(AreaCityActivity.this).setSaleType(1);
                        } else {
                            saleString = "amount";
                            sale_text.setText("销额");
                            new SharedPreferencesUtils(AreaCityActivity.this).setSaleType(2);
                        }
                        break;
                    case 2:
                        weekStringTemp = weeks.get(wheelview_single1.getCurrentPosition());
                        week_text.setText(weekString);
                        switch (weekStringTemp) {
                            case "近四周":
                                week_text.setText("近四周");
                                weekString = "fourWeek";
                                new SharedPreferencesUtils(AreaCityActivity.this).setWeekType("近四周");
                                break;
                            case "近八周":
                                week_text.setText("近八周");
                                weekString = "eightWeek";
                                new SharedPreferencesUtils(AreaCityActivity.this).setWeekType("近八周");
                                break;
                            case "本年累计":
                                week_text.setText("本年累计");
                                weekString = "year";
                                new SharedPreferencesUtils(AreaCityActivity.this).setWeekType("本年累计");
                                break;
                            case "当前周":
                                week_text.setText("当前周");
                                weekString = "current";
                                new SharedPreferencesUtils(AreaCityActivity.this).setWeekType("当前周");
                                break;
                            default:
                                week_text.setText("当前周");
                                weekString = "current";
                                new SharedPreferencesUtils(AreaCityActivity.this).setWeekType("当前周");
                                break;
                        }
                        break;
                }
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                getBrandScaleBasisRatio();
            }
        });
    }

    /**
     * api/scale/brandScaleBasisRatio
     */
    private void getBrandScaleBasisRatio() {
        loading.setVisibility(View.VISIBLE);
        String url = AvcConstants.URLHeaderBase + URL_Area;
        HashMap<String, Object> map = new HashMap<>();
        map.put("timeType", weekString);
        map.put("category", category);
        map.put("lastWeek", new SharedPreferencesUtils(this).getNewWeek());
        ThreadPoolUtils.execute(new JsonRunnable(AreaCityActivity.this, "HTTPGET", url, handler, map, 1));
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case -1:
                    loading.setVisibility(View.GONE);
                    break;
                case 1:
                    loading.setVisibility(View.GONE);
                    AreaInfo ai = new Gson().fromJson(msg.obj.toString(),AreaInfo.class);
                    list.clear();
                    lv.setOnItemClickListener(AreaCityActivity.this);
                    for (Map.Entry<String, Map<String, List<AreaInfo.CityBean>>> entry : ai.getReturnValue().getOfflineData().entrySet()) {
                        if (entry.getKey().equals(bigregion)){
                            for(Map.Entry<String,List<AreaInfo.CityBean>> entry1 :entry.getValue().entrySet()){
                                for(AreaInfo.CityBean bean :entry1.getValue()) {
                                    if(bean.getOfficeName().equals(office) && (!(bean.getCityName().equals("all")))){
                                        AreaListViewInfo listViewInfo = new AreaListViewInfo();
                                        listViewInfo.setBigRegin(bean.getCityName());
                                        if(saleString.equals("amount")){
                                            listViewInfo.setBasicRatio(bean.getAmountMarketShareBasisRatio());
                                            listViewInfo.setMarketShare(bean.getAmountMarketShare());
                                            listViewInfo.setRelaRation(bean.getAmountMarketShareLinkRelativeRatio());
                                        }else{
                                            listViewInfo.setBasicRatio(bean.getVolumeMarketShareBasisRatio());
                                            listViewInfo.setMarketShare(bean.getVolumeMarketShare());
                                            listViewInfo.setRelaRation(bean.getVolumeMarketShareLinkRelativeRatio());
                                        }
                                        list.add(listViewInfo);
                                    }
                                }
                                continue;
                            }
                        }
                    }
                    adapter.notifyDataSetChanged();
                    if(weekString.equals("current")){
                        week_text.setText(ai.getMessage().toString().trim());
                    }
                    break;
                case -22:
                    loading.setVisibility(View.GONE);
                    Intent intent = new Intent ();
                    intent.setClass (AreaCityActivity.this, Login_Activity.class );
                    intent.setFlags ( Intent.FLAG_ACTIVITY_CLEAR_TASK );  //注意本行的FLAG设置
                    AreaCityActivity.this.finish ();
                    startActivity ( intent );
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

}